package com.jn.rxjava.views;

import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.jn.rxjava.R;
import com.jn.rxjava.adapter.RetrofitClient;
import com.jn.rxjava.service.ApiService;
import com.jn.rxjava.service.NewsResponse;
import java.util.List;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class NewsActivity extends AppCompatActivity {
    private TextView textViewNews, textViewWeiyu, textViewDate, textViewCreatedAt;
    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news);

        textViewNews = findViewById(R.id.textViewNews);
        textViewWeiyu = findViewById(R.id.textViewWeiyu);
        textViewDate = findViewById(R.id.textViewDate);
        textViewCreatedAt = findViewById(R.id.textViewCreatedAt);
        imageView = findViewById(R.id.imageView);

        fetchNewsData();
    }

    private void fetchNewsData() {
        ApiService apiService = RetrofitClient.getRetrofitInstance().create(ApiService.class);
        apiService.getNews()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    Log.d("NewsActivity", "API响应: " + new Gson().toJson(response));
                    displayNewsData(response);
                }, throwable -> {
                    Log.e("NewsActivity", "获取新闻失败", throwable);
                    textViewNews.setText("获取新闻失败: " + throwable.getMessage());
                });
    }

    private void displayNewsData(NewsResponse response) {
        if (response.getCode() == 200) {
            NewsResponse.Result result = response.getResult();
            List<String> newsList = result.getNews();
            StringBuilder newsStringBuilder = new StringBuilder();

            for (String news : newsList) {
                newsStringBuilder.append(news).append("\n\n");
            }

            String newsText = newsStringBuilder.toString();
            String weiyuText = result.getWeiyu();
            String dateText = "Date: " + result.getDate();
            String createdAtText = "Created At: " + result.getCreatedAt();

            textViewNews.setText(newsText);
            textViewWeiyu.setText(weiyuText);
            Glide.with(this)
                    .load(result.getImage())
                    .into(imageView);
            textViewDate.setText(dateText);
            textViewCreatedAt.setText(createdAtText);
        } else {
            textViewNews.setText("错误信息: " + response.getMsg());
        }
    }
}